%%% File    : exchanger_sup.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 29 Mar 2011 by  <>

-module(exchanger_sup).

-behaviour(gen_server).

-export([start_link/0]).

-export([start_exchanger/1, stop_exchanger/1]).

-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	terminate/2, code_change/3]).


-record(state, {type,
		exchanger,
	        restart}).

%%-------
start_exchanger(Node) when is_atom(Node) ->
    gen_server:call({global, ?MODULE}, {start_exchanger, Node});
start_exchanger(_) ->
    {error, badarg}.

stop_exchanger(Node) when is_atom(Node) ->
    gen_server:call({global, ?MODULE}, {stop_exchanger, Node});
stop_exchanger(_) ->
    {error, badarg}.

start_link() ->
    gen_server:start_link({global, ?MODULE}, ?MODULE, [], []).

%%-----
init([]) ->
    process_flag(trap_exit, true),
    pg2:create(exchanger),
    S = #state{type=exchanger,
	      exchanger=[],  %%[{node, pid}]
	      restart=3},
    {ok, S}.

handle_call({start_exchanger, Node}, _From, S) ->
    {Res, Ns} = do_start(Node, S),
    {reply, Res, Ns};

handle_call({stop_exchanger, Node}, _From, S) ->
    {Res, Ns} = do_stop(Node, S),
    {reply, Res, Ns};

handle_call(_Req, _From, S) ->
    {reply, ok, S}.

handle_cast({redirect, Node, Pid}, S=#state{exchanger=Ex}) ->
    link(Pid),
    {noreply, S#state{exchanger=[{Node, Pid}|Ex]}};

handle_cast(_Msg, S) ->
    {noreply, S}.

handle_info({'EXIT', _, normal}, S) ->
    {noreply, S};

handle_info({'EXIT', Pid, _}, S=#state{exchanger=Ex}) ->
    case lists:keysearch(Pid, 2, Ex) of
	false ->
	    {noreply, S};
	{value, {Node, Pid}} ->
	    Ns = do_restart(Node, S),
	    {noreply, Ns}
    end;

handle_info(_Info, S) ->
    {noreply, S}.

terminate(_Reason, _S) -> 
    ok.

code_change(_Oldvsn, S, _Extra) ->
    {ok, S}.
  
%%------
do_start(Node, S=#state{exchanger=Ex}) ->
    case lists:keysearch(Node, 1, Ex) of
	{value, _} ->
	    {{error, exist}, S};
	false ->
	    Res = rpc:call(Node, exchanger, start, [self()]),
	    case Res of
		{ok, Pid} ->
		    link(Pid),
		    pg2:join(exchanger, Pid),
		    {ok, S#state{exchanger=[{Node, Pid}|Ex]}};
		Err ->
		    {{error, Err}, S}
            end
     end.

do_stop(Node, S=#state{exchanger=Ex}) ->
    case lists:keysearch(Node, 1, Ex) of
	false ->
	    {{error, noexist}, S};
	{value, {Node, Pid}} ->
	    do_exit(Pid),
	    {ok, S#state{exchanger=lists:keydelete(Node, 1, Ex)}}
    end.

do_exit(Pid) ->
    gen_server:cast(Pid, {do_stop, self()}).

do_restart(Node, S=#state{exchanger=Ex}) ->
    Res = rpc:call(Node, exchanger, start, [self()]),
    case Res of
	{ok, Pid} ->
	    link(Pid),
	    pg2:join(exchanger, Pid),
	    S#state{exchanger=[{Node, Pid}|lists:keydelete(Node,1,Ex)]};
	Err ->
	    io:format("restart exchanger on node :~p failed for reason ~p~n", [Node, Err]),
	    S#state{exchanger=lists:keydelete(Node, 1, Ex)} 
    end.
